package com.portal.backend.controller;

import com.portal.backend.payload.ArticleRequest;
import com.portal.backend.payload.ArticleResponse;
import com.portal.backend.service.ArticleService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.portal.backend.security.UserPrincipal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import com.portal.backend.payload.UserSummary;
import java.util.List;

import javax.validation.Valid;
import java.util.Collections;

@RestController
@RequestMapping("/api/articles")
@CrossOrigin(origins = "*", maxAge = 3600)
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @PostMapping
    @PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
    public ResponseEntity<ArticleResponse> createArticle(@Valid @RequestBody ArticleRequest articleRequest) {
        ArticleResponse articleResponse = articleService.createArticle(articleRequest);
        return new ResponseEntity<>(articleResponse, HttpStatus.CREATED);
    }

    @GetMapping("/{id}")
    public ResponseEntity<ArticleResponse> getArticleById(@PathVariable Long id) {
        ArticleResponse articleResponse = articleService.getArticleById(id);
        // 获取当前用户点赞状态
        try {
            UserPrincipal userPrincipal = (UserPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            boolean liked = articleService.hasLiked(id, userPrincipal.getId());
            articleResponse.setLikedByCurrentUser(liked);
        } catch (Exception e) {
            articleResponse.setLikedByCurrentUser(false);
        }
        return ResponseEntity.ok(articleResponse);
    }

    @GetMapping
    public IPage<ArticleResponse> getAllArticles(@RequestParam(defaultValue = "1") long current,
                                                 @RequestParam(defaultValue = "10") long size) {
        return articleService.getAllArticles(current, size);
    }

    @GetMapping("/user/{userId}")
    public IPage<ArticleResponse> getArticlesByAuthor(@PathVariable Long userId,
                                                     @RequestParam(defaultValue = "1") long current,
                                                     @RequestParam(defaultValue = "10") long size) {
        return articleService.getArticlesByAuthor(userId, current, size);
    }

    @PutMapping("/{id}")
    @PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
    public ResponseEntity<ArticleResponse> updateArticle(@PathVariable Long id, @Valid @RequestBody ArticleRequest articleRequest) {
        ArticleResponse articleResponse = articleService.updateArticle(id, articleRequest);
        return ResponseEntity.ok(articleResponse);
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
    public ResponseEntity<?> deleteArticle(@PathVariable Long id) {
        articleService.deleteArticle(id);
        return ResponseEntity.ok("Article deleted successfully");
    }

    @PostMapping("/{id}/like")
    @PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
    public ResponseEntity<?> likeArticle(@PathVariable Long id) {
        UserPrincipal userPrincipal = (UserPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Long userId = userPrincipal.getId();
        boolean liked = articleService.toggleLike(id, userId);
        return ResponseEntity.ok(Collections.singletonMap("liked", liked));
    }

    @GetMapping("/{id}/like-users")
    public List<UserSummary> getLikeUsers(@PathVariable Long id) {
        return articleService.getLikeUsers(id);
    }
} 